<?php

namespace app\admin\service;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use think\admin\Service;
use think\facade\Db;
use think\facade\Log;

/**
 * 消息通知
 * Class BaseUserMessageService
 * @package app\data\service
 */
class WxWorkService extends Service
{
    /**
     * 小程序配置参数
     * @var array
     */
    private $config;
    private $contacts;

    /**
     * 接口服务初始化
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function initialize()
    {
        $this->config = config('office_work');
        $this->config = [
            'corp_id' => $this->config['corp_id'],
            'secret' => $this->config['agent_secret'],
        ];
        $this->contacts = Factory::work($this->config);
    }

    /**
     * 获取部门ID列表
     * @return void
     */
    public function departmentList()
    {
        $departmentList = $this->contacts->department->list();
        foreach ($departmentList['department'] ?? [] as $department) {
            $departmentInsertData[] = [
                'id' => $department['id'],
                'name' => $department['name'],
                'parentid' => $department['parentid'],
                'order' => $department['order'],
            ];
        }

        if (!empty($departmentInsertData)) {
            Db::execute('TRUNCATE TABLE `work_department`');
            $this->app->db->name('work_department')->insertAll($departmentInsertData);
        }
    }

    /**
     * 删除部门
     * @param $id
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function deleteDepartment($id)
    {
        $this->app->db->name('work_department')->where('id', $id)->delete();
    }

    /**
     * 获取员工列表数据
     * @param $contacts
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserDetailedDepartmentUsers()
    {
        $users = $this->contacts->user->getDetailedDepartmentUsers(1, true);

        $userIds = array_column($users['userlist'] ?? [], 'userid');
        $existUserIds = $this->app->db->name('work_user')->whereIn('userid', $userIds)->select()->toArray();
        $existUserIds = array_column($existUserIds, 'userid');

        foreach ($users['userlist'] ?? [] as $user) {
            $data = [
                'username' => $user['userid'],
                'name' => $user['name'],
                'userid' => $user['userid'],
                'department'  => implode(',', $user['department']),
                'mobile'         => $user['telephone'],
                'status'         => $user['status'],
            ];
            if (!empty($user['avatar'])) {
                $data['avatar'] = $user['avatar'];
            }
            if (!empty($user['qr_code'])) {
                $data['qr_code'] = $user['qr_code'];
            }

            if (in_array($user['userid'], $existUserIds)) {
                $updateUpdateData[] = $data;
            } else {
                $data['password'] = md5($user['userid']);
                $userInsertData[] = $data;
            }
        }

        if (!empty($userInsertData)) {
            $this->app->db->name('work_user')->insertAll($userInsertData);
        }
        if (!empty($updateUpdateData)) {
            foreach ($updateUpdateData as $updateUpdateDataItem) {
                $this->app->db->name('work_user')->where('userid', $updateUpdateDataItem['userid'])->update($updateUpdateDataItem);
            }
        }

    }

    /**
     * 获取员工信息
     * @param $userid
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function getUserInfo($userid)
    {
        $user = $this->contacts->user->get($userid);
        if (empty($user['userid'])) {
            Log::error('查无用户信息' . $userid);
            return false;
        }
        $data = [
            'username' => $user['userid'],
            'name' => $user['name'],
            'userid' => $user['userid'],
            'department'  => implode(',', $user['department']),
            'mobile'         => $user['telephone'],
            'status'         => $user['status'],
        ];
        if (!empty($user['avatar'])) {
            $data['avatar'] = $user['avatar'];
        }
        if (!empty($user['qr_code'])) {
            $data['qr_code'] = $user['qr_code'];
        }

        $dbUser = $this->app->db->name('work_user')->where('userid', $userid)->findOrEmpty();
        if ($dbUser) {
            $this->app->db->name('work_user')->where('userid', $userid)->update($data);
        } else {
            $data['password'] = md5($data['userid']);
            $this->app->db->name('work_user')->insert($data);
        }
    }

    /**
     * 删除员工
     * @param $userid
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function deleteUser($userid)
    {
        $this->app->db->name('work_user')->where('userid', $userid)->update(['status' => 5]);
    }

    /**
     * 发送消息
     * @param $userid
     * @param $message
     * @return true
     */
    public function sendMessageTextByUserid($userid, $message)
    {
        if (env('APP_DEBUG')) {
            return true;
        }

        // 获取 Messenger 实例
        $messenger = $this->contacts->messenger;

        // 准备消息
        $message = new Text($message);

        // 发送
        $result = $messenger->message($message)->toUser($userid)->ofAgent(config('office_work.agent_id'))->send();

        if (!empty($result['errcode'])) {
            Log::error('企业微信发送消息失败 ' . json_encode($result));
        }

        return $result;
    }
}